package routower

import (
	"context"
	"wzgames/internal/app"
	"wzgames/internal/gloader"
	"wzgames/internal/model/gamep"
	"wzgames/internal/response"
	rt "wzgames/internal/services/routower"
	"wzgames/pkg/actor/actorservice"
)

func RunServer() error {
	bootc := gloader.BootConfig()
	return app.Start(bootc,
		app.BeforeStart(func(ctx context.Context) error {
			err := gloader.CommMgr().LoadSysConfig()
			if err != nil {
				return err
			}
			return gloader.CommMgr().WatchCommConfig()
		}, func(ctx context.Context) error {
			err := gloader.CommMgr().InitWdb()
			if err == nil {
				err = gloader.CommMgr().InitRedis()
			}
			if err == nil {
				err = gloader.CommMgr().InitNats()
			}
			if err != nil {
				return err
			}
			err = actorservice.StartService(rt.Actor())
			if err != nil {
				return err
			}
			response.InitBetNotePool()
			response.InitElapsePacketPool()
			return gloader.GameMgr().LoadRouletteInst(true, rt.InitInstManager().OnInstChange)
		}, func(ctx context.Context) error {
			err := gloader.GameMgr().InitGameInst(gamep.RouletteGrp, rt.InitInstManager().InitInst)
			if err != nil {
				return err
			}
			gloader.GameMgr().ListenChange()
			return gloader.GameMgr().WatchRouletteInsts()
		}),
		app.AfterStart(func(ctx context.Context) error {
			actorservice.Send(rt.Actor().GetPID(), rt.StartElection{})
			return nil
		}),
		app.AfterStop(func(ctx context.Context) error {
			rt.Actor().OnDestroy()
			rt.InitInstManager().Destroy()
			gloader.Res().Stop()
			return nil
		}),
	)
}
